// 34.在排序数组中查找元素的第一个和最后一个位置
package LeetcodeHot100;

public class Solution034 {
    int[] result = new int[] { -1, -1 };

    public int[] searchRange(int[] nums, int target) {
        binarySearch(nums, target, 0, nums.length - 1);
        return result;
    }

    private void binarySearch(int[] nums, int target, int left, int right) {
        if (left > right)
            return;
        int mid = (left + right) / 2;
        if (nums[mid] == target && (mid - 1 < 0 || nums[mid - 1] != target)) {
            result[0] = mid;
        }
        if (nums[mid] == target && (mid + 1 > nums.length - 1 || nums[mid + 1] != target)) {
            result[1] = mid;
        }
        if (nums[mid] == target) {
            binarySearch(nums, target, left, mid - 1);
            binarySearch(nums, target, mid + 1, right);
        } else if (nums[mid] < target) {
            binarySearch(nums, target, mid + 1, right);
        } else {
            binarySearch(nums, target, left, mid - 1);
        }
    }
}
